簡體   English   中英

Python Tkinter阻止執行按鈕命令

[英]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()

因此,以下是發生的情況的細分:

  1. 定義按鈕后,將調用Pistol函數,它將所有功能添加到Pistol按鈕中,包括更改文本以及添加按下時將調用的功能。
  2. 當按下按鈕時,它將調用pistolCycle。 手槍循環的作用是獲取“計數器”值,並將按鈕的文本更改為與之關聯的列表中的項目。 EG,當計數器為0時,顯示.44手槍。
  3. 每次調用pistolCycle時,該計數器加1,這意味着下次調用它時,它將顯示列表中的下一項。

現在,使用全局變量會變得混亂。 我已經為您提供了基本框架,因此您也許可以使用自己的邏輯來獲取變量“ counter”,每次將其傳遞到pistolCycle中(例如,EG,pistolCycle(counter))

您需要制作一個單獨的計數器和循環功能,以使所有按鈕正常工作。

希望對您有所幫助!!

PS:pistolCycle函數中的if語句表示當列表中不存在該項目時,它將不會嘗試獲取該項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM