匯入的模塊可以讓主模塊呼叫一個函式嗎?我創建了一個序列圖,并且我有一個準系統代碼示例來說明我的意思:
主要的:
import test2
def function():
do sth
測驗2:
import tkinter as tk
window = tk.Tk()
test = tk.Button(master = window, text = "hdsd", command = # call function of main program)
test.grid(row = 0, column = 0)
window.mainloop()
uj5u.com熱心網友回復:
這樣做的方法是設計您匯入的代碼,以便您只匯入物件(函式、類、常量)而不是運行代碼。然后,一旦有了函式或類,就可以將其他函式或物件傳遞給它們。
例如,考慮這個main.py:
import test2
def function():
do sth
test2.create_gui(function)
test2.py可能看起來像這樣:
def create_gui(func):
window = tk.Tk()
test = tk.Button(master = window, text = "hdsd", command = func)
test.grid(row = 0, column = 0)
window.mainloop()
可以說,更好的解決方案是對main.py和test2.py中的代碼使用類。通過將所有函式添加到一個類中,您可以傳遞一個實體,您的 GUI 將可以訪問所有函式。
主檔案
from test2 import GUI
class Main():
def __init__(self):
self.gui = GUI(self)
def function(self):
do sth
def another_function(self):
do sth
if __name__ == "__main__":
main = Main()
main.gui.start()
測驗2.py
import tkinter as tk
class GUI(tk.Tk):
def __init__(self, main):
super().__init__()
test1 = tk.Button(self, text="hdsd", command=main.function)
test2 = tk.Button(self, text="sdhd", command=main.another_function)
test1.grid(row=0, column=0)
test2.grid(row=0, column=1)
def start(self):
self.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421365.html
標籤:
下一篇:兩個預定義函式的組合(分段)函式
