[英]Calling Functions within Classes from Tkinter Buttons
我目前正在嘗試在我的代碼中使用我以前沒有使用過的類。 我的目標是當按下電源按鈕時,系統會檢查電源是否打開,如果沒有,則返回“Power On”,對於 Power Off 也是如此,依此類推。 按下按鈕時我目前正在苦苦掙扎我不確定如何使用指定文本(例如“PWR”)向控制范圍內的 function 發送命令下面是我的代碼非常感謝任何幫助謝謝
import tkinter as tk
window = tk.Tk()
class Power:
def __init__(self, x):
if x == 0:
# Run def control
# Change function in def control to Power
print ("Power On")
if x == 1:
# Run def control
# Change function in def control to Power
print("Power Off")
if x == 2:
# Run def Control
# Change Function to Inp
# Add which input has been selected to the end of the return
print ("Input 1")
if x == 3:
# Run def Control
# Change Function to Inp
# Add which input has been selected to the end of the return
print ("Input 2")
def control(self, function):
if function[:3] == "PWR":
if "on" in function.lower():
return ("Power On")
elif "off" in function.lower():
return("Power Off")
else:
return ("Power Error")
elif function[:3] == 'INP':
inp = function[3:]
return 'Input ' + inp
CtrlBtnsTxt = ["Power On", "Power Off", "Input 1", "Input 2"]
for i in range (4):
CtrlBtns = tk.Button(window, width = 10, height = 5, text = CtrlBtnsTxt[i], command = lambda x = i: Power (x) )
CtrlBtns.grid (row = i, column = 0)
window.mainloop()
class 實例跨命令持久化會更好。 這樣你就可以簡單地記住當前的按鈕狀態,並在下次調用時使用它來調整行為:
import tkinter as tk
window = tk.Tk()
class Power:
# ====> Memorizes states
power = False
curInput = 0
# ====> Replace __init__ by a method you can call without creating a new instance
def command(self, x):
if x == 0:
print (self.control("PWR on"))
if x == 1:
print (self.control("PWR off"))
if x == 2:
print (self.control("INP 1"))
if x == 3:
print (self.control("INP 2"))
def control(self, function):
if function[:3] == "PWR":
# ====> Includes the stored state in the tests and stores the new state
if "on" in function.lower() and self.power == False:
self.power = True
return "Power On"
# ====> Idem
elif "off" in function.lower() and self.power == True
self.power = False
return "Power Off"
else:
return ("Power Error")
elif function[:3] == 'INP':
inp = function[3:]
# ====> Optionally you can do the same for the input
if (inp == self.curInput): return 'Input already set'
self.curInput = inp
return 'Input ' + inp
CtrlBtnsTxt = ["Power On", "Power Off", "Input 1", "Input 2"]
# ====> Creates a unique instance of the class and uses it below
power = Power()
for i in range (4):
CtrlBtns = tk.Button(window, width = 10, height = 5, text = CtrlBtnsTxt[i], command = lambda x = i: power.command(x) )
CtrlBtns.grid (row = i, column = 0)
window.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.