0

我在 tkinter 中有一个复选框工具栏菜单选项。每当我单击该选项时,它都会启用自动换行并在其旁边放置一个复选标记。

# Toggle Word Wrap Function
def ToggleWordWrap(*args):
    # If there is no word wrap then add word wrap
    if TextBox.cget("wrap") == "none":
        TextBox.configure(wrap="word")
    # If there is word wrap then take out word wrap
    elif TextBox.cget("wrap") == "word":
        TextBox.configure(wrap="none")

# Check Marks for Options in Tools Menu
WordWrap_CheckMark = BooleanVar()
WordWrap_CheckMark.set(False)

# Tools Option for Menu Bar
ToolsOption = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="Tools", menu=ToolsOption, underline=0)
ToolsOption.add_command(label="Word Count")
ToolsOption.add_checkbutton(label="Toggle Word Wrap", onvalue=1, offvalue=0, variable=WordWrap_CheckMark, command=ToggleWordWrap)

我还决定我应该在函数中添加一个键盘绑定 Alt-Z。

# Toggle Word Wrap Function
def ToggleWordWrap(*args):
    # If there is no word wrap then add word wrap
    if TextBox.cget("wrap") == "none":
        TextBox.configure(wrap="word")
    # If there is word wrap then take out word wrap
    elif TextBox.cget("wrap") == "word":
        TextBox.configure(wrap="none")
root.bind("<Alt-Key-z>", ToggleWordWrap)

# Check Marks for Options in Tools Menu
WordWrap_CheckMark = BooleanVar()
WordWrap_CheckMark.set(False)

# Tools Option for Menu Bar
ToolsOption = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="Tools", menu=ToolsOption, underline=0)
ToolsOption.add_command(label="Word Count")
ToolsOption.add_checkbutton(label="Toggle Word Wrap", onvalue=1, offvalue=0, variable=WordWrap_CheckMark, command=ToggleWordWrap, accelerator="Alt-Z")

每当我使用键盘绑定时,它都不会打开复选标记。我将如何解决这个问题?

4

1 回答 1

1

WordWrap_CheckMark当自动换行打开时,您需要设置True。

这是您的功能:

def toggleWordWrap(event=None):
   
   if textBox.cget("wrap") == "none":
        textBox.configure(wrap="word")
        WordWrap_CheckMark.set(True)
    # If there is word wrap then take out word wrap

   elif textBox.cget("wrap") == "word":
        textBox.configure(wrap="none")
        WordWrap_CheckMark.set(False)

这是完整的示例:

from tkinter import *

def toggleWordWrap(event=None):
   
   if textBox.cget("wrap") == "none":
        textBox.configure(wrap="word")
        WordWrap_CheckMark.set(True)
    # If there is word wrap then take out word wrap

   elif textBox.cget("wrap") == "word":
        textBox.configure(wrap="none")
        WordWrap_CheckMark.set(False)

root = Tk()

root.bind_all("<Alt-Key-z>", toggleWordWrap)  # just Alt-z will also work fine

WordWrap_CheckMark = BooleanVar()
WordWrap_CheckMark.set(False)

menuBar = Menu(root)

tools = Menu(menuBar, tearoff=0)
tools.add_command(label='Word Count')
tools.add_checkbutton(label="Toggle Word Wrap", onvalue=1, offvalue=0, variable=WordWrap_CheckMark, command=toggleWordWrap, accelerator="Alt-Z")

menuBar.add_cascade(label ='Tools', menu=tools)

textBox = Text(root, wrap="none")
textBox.pack()

root.config(menu = menuBar)
root.mainloop()

于 2021-03-05T02:51:25.137 回答