如何在 Tkinter 中切换按钮的功能?

How to switch functions for buttons in Tkinter?

所以我想制作一个程序,当我点击按钮时,它应该让文本框自动换行,但是当我再次点击按钮时,它应该反转或切换它,这样就没有自动换行.

到目前为止,这是我的代码:

from tkinter import *


root = Tk()
root.geometry("600x600")

textBox = Text(root, width=500, height=500, wrap="none")

def doSomething():
    textBox.configure(wrap="word")
    # When I click it twice the wrap="none"

button = Button(root, text="Click Here", command=doSomething)
button.pack()


root.mainloop()

因此,当我单击该按钮时,它应该将换行更改为 word,但是当我再次单击它时,它应该将换行更改为 none。那我该怎么做呢?

只需将您的函数更改为:

def doSomething():
    if textBox.cget("wrap") == "none":
        textBox.configure(wrap="word")
    elif textBox.cget("wrap") =="word":
        textBox.configure(wrap="none")

您可以使用来自 tkinter 的 StringVar()

#!/usr/bin/env python
from tkinter import *

root = Tk()
root.geometry("600x600")
var_button = StringVar()
var_button.set("word")

textBox = Text(root, width=500, height=500, wrap="none")

def doSomething():
    if var_button.get() == "word":       
        var_button.set("none")
        # When I click it twice the wrap="none"
    else:        
        textBox.configure(wrap="word")
        var_button.set("word") 
    print(f'textBox {var_button.get()}')

button = Button(root, text="Click Here", command=doSomething)
button.pack()