[英]Python Tkinter preventing button command from executing
当试图按原始的6个按钮之一调用适当的函数来重命名按钮时,我试图获取以下代码的最后几行。 我尝试将命令行更改为button [0] .command = Pistols()。 我也尝试过使用带有变量(例如x == 1)的if循环来确定是否按下按钮x时将x设为1,而for循环将调用函数Pistols,但没有成功。 但是,该按钮会自动调用该函数,并将第一个按钮重命名为“ .44手枪”,而不是应为“手枪”的名称。 我不希望仅执行命令并在按下时调用该函数。 我知道tkinter会自动查找正在调用的函数并运行其代码。 我该如何延迟或以另一种方式处理此问题,以使功能代码仅在按下时执行。 提前致谢!
from tkinter import *
buttons = []
clm = [1,2,1,2,1,2]
rw = [1,1,2,2,3,3]
btnmain_list = ['Pistol','Rifle','Assult Rifle','Submachine Gun','Heavy Weapon','Plasma Weapons']
btnpistol_list = ['.44 Pistol', '10mm Pistol', 'Pipe Bolt-Action Pistol','Flare Gun', 'Pipe Pistol', 'Pipe Revolver']
btnrifle_list = []
btnasrifle_list = []
btnsubgun_list = []
btnheavy_list = []
btnplasma_list = []
ms = Tk()
ms.title('Fallout 4 weapon mods and needed materials')
ms.geometry('450x400')
placement = Frame(ms)
placement.grid()
class Guns:
def Pistols ():
buttons[0] = Button(placement,height = '5',width = '20', text = btnpistol_list[0])
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
buttons[0].command = Pistols()
我通过将类更改为此找到了一个解决方案:
class Guns:
global counter
counter = 0
def pistolCycle():
global counter
buttons[0].config(text=btnpistol_list[counter])
if counter == len(btnpistol_list)-1:
counter=0
counter = counter+1
def Pistols ():
buttons[0] = Button(placement, height = '5',width = '20', text="Pistols", command = lambda: Guns.pistolCycle() )
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
Pistols()
因此,以下是发生的情况的细分:
现在,使用全局变量会变得混乱。 我已经为您提供了基本框架,因此您也许可以使用自己的逻辑来获取变量“ counter”,每次将其传递到pistolCycle中(例如,EG,pistolCycle(counter))
您需要制作一个单独的计数器和循环功能,以使所有按钮正常工作。
希望对您有所帮助!!
PS:pistolCycle函数中的if语句表示当列表中不存在该项目时,它将不会尝试获取该项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.