我在“TTK 筆記本在匯入的標簽之間共享資料”的標題下發現了一篇非常有趣的帖子。
這是鏈接:[https://stackoverflow.com/questions/36032712/ttk-notebook-share-data-between-imported-tabs][1]
這是主要的應用程式:
我已經按照那里的描述創建了并且它有效。但是如何在這兩個類之間共享資料呢?
例如,如果我將以下代碼寫入主應用程式:
self.hello = "Hello World"
page1 = Page1(self.notebook, self.hello)
page2 = Page2(self.notebook, self.hello)
我收到錯誤訊息:
page1 = Page1(self.notebook, self.app_data)
TypeError: init () 需要 2 個位置引數,但給出了 3 個
我已經研究了好幾天了,但不幸的是我不明白錯誤在哪里。如果有人能在這里幫助我,我會很高興。
這是主要的應用程式(main.py):
import tkinter as tk
from tkinter import ttk
from page1 import Page1
from page2 import Page2
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill="both", expand=True)
page1 = Page1(self.notebook)
page2 = Page2(self.notebook)
self.notebook.add(page1, text="Tab 1")
self.notebook.add(page2, text="Tab 2")
self.hello = "Hello World"
page1 = Page1(self.notebook, self.hello)
page2 = Page2(self.notebook, self.hello)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
這是第 1 頁“page1.py”:
import tkinter as tk
class Page1(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Das ist Tab 1" self.hello)
label.pack(fill ="both", expand=True, padx=20, pady=10)
這是第 2 頁“page2.py”:
import tkinter as tk
class Page2(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Das ist Tab 2" self.hello)
label.pack(fill ="both", expand=True, padx=20, pady=10)
uj5u.com熱心網友回復:
錯誤告訴您究竟出了什么問題:
page1 = Page1(self.notebook, self.app_data)
TypeError: __init()__ takes 2 positional arguments but 3 were given
正如我們所見,您Page2.__init__需要兩個位置引數:self和parent。當您這樣做時Page1(self.notebook, self.app_data), ,self會自動__init__作為第一個引數傳遞給。self.notebook作為 傳遞parent,并且沒有第三個引數可以接受self.app_data。
您需要修改__init__以接受資料引數:
class Page2(tk.Frame):
def __init__(self, parent, app_data):
tk.Frame.__init__(self, parent)
self.app_data = app_data
請注意,這將導致不同的行失敗,因為您也可以在Page2沒有額外引數的情況下呼叫:
page1 = Page1(self.notebook)
不清楚為什么要創建page1兩次,但是您需要在創建方式上保持一致。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393596.html
上一篇:不能關閉一個視窗并保持其他打開
