我一直在努力完成我正在研究的這個部分的專案。每當用戶單擊第二個按鈕時,我都想將 Button 命令函式的結果用于另一個按鈕命令函式。下面附上示例代碼。這個慣用腳本的想法是,第一個按鈕用于坐標校準(通過計算它們各自的比率來計算實際空間與計算機螢屏空間),第二個按鈕將使用該校準函式的結果來“轉換”坐標。第二個按鈕的輸入。忽略我在這里反映的虛擬操作。
from tkinter import *
import tkinter as tk
root = Tk()
def solve1():
x = [1, 2, 3]
print(x)
def solve2():
y = [4, 5, 6]
print(y)
z = x y
print(z) # this is not working
Button1 = Button(root, text="Opt 1", command=solve1).grid(row=1, column=1, sticky="w")
Button2 = Button(root, text="Opt 2", command=solve2).grid(row=2, column=1, sticky="w")
root.mainloop()
代碼不起作用,因為 python 說 solve1 未定義。我是編程世界的新手,因此感謝任何共享的想法。PS:我需要提取這兩個函式的結果報告,所以不能合并成一個函式
uj5u.com熱心網友回復:
簡單、笨拙的方法是將變數定義為全域變數。例如(還有一些其他的最佳實踐改進):
import tkinter as tk
root = tk.Tk()
def solve1():
global x
x = [1, 2, 3]
print(x)
def solve2():
y = [4, 5, 6]
print(y)
z = x y
print(z)
Button1 = tk.Button(root, text="Opt 1", command=solve1)
Button1.grid(row=1, column=1, sticky="w")
Button2 = tk.Button(root, text="Opt 2", command=solve2)
Button2.grid(row=2, column=1, sticky="w")
root.mainloop()
正確的方法是創建一個類:
import tkinter as tk
class MSDS(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Button1 = tk.Button(self, text="Opt 1", command=self.solve1)
Button1.grid(row=1, column=1, sticky="w")
Button2 = tk.Button(self, text="Opt 2", command=self.solve2)
Button2.grid(row=2, column=1, sticky="w")
def solve1(self):
self.x = [1, 2, 3]
print(self.x)
def solve2():
y = [4, 5, 6]
print(y)
z = self.x y
print(z)
def main():
root = tk.Tk()
win = MSDS(root)
win.pack()
root.mainloop()
if __name__ == "__main__":
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345026.html
