python button change text after click

后端 未结 1 1915
夕颜
夕颜 2021-01-23 07:29

i want to make a Button that changes the displayed text(number) after every click and returns the valure defined in the function, because i want to work with the displayed varia

相关标签:
1条回答
  • 2021-01-23 07:44

    First

    btn = tk.Button(...).grid(..)
    

    assigns None to btn because grid() returns None

    use

    btn = tk.Button(...)
    btn.grid(...)
    

    Now you can change text on button using btn['text'] = "new text" or btn.config(text="new text")

    import tkinter as tk
    
    # --- functions ---
    
    def text_change():
        global text
    
        text += 1
    
        if text > 4:
            text = 1
    
        print("changed to:", text)
    
        #btn['text'] = text
        btn.config(text=text)
    
    def text_print():
        print("current:", text)
    
    # --- main ---
    
    text = 0
    
    root = tk.Tk()
    
    btn = tk.Button(text="1,2,3 or 4", command=text_change, width=10, height=3)
    btn.grid(row=1, column=1)
    
    btn2 = tk.Button(text="SHOW", command=text_print, width=10, height=3)
    btn2.grid(row=2, column=1)
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题