如何创建一个 tkinter 切换按钮?

新手上路,请多包涵

我一直在使用 Python 2.7 中的 Tkinter 开发文本编辑器。我试图实现的一个功能是夜间模式,用户可以在黑色背景和浅色背景之间切换,只需单击切换按钮即可从浅色切换到深色。

 from Tkinter import *

from tkSimpleDialog import askstring

from tkFileDialog   import asksaveasfilename
from tkFileDialog import askopenfilename

from tkMessageBox import askokcancel

Window = Tk()
Window.title("TekstEDIT")
index = 0

class Editor(ScrolledText):

    Button(frm, text='Night-Mode',  command=self.onNightMode).pack(side=LEFT)

    def onNightMode(self):
    if index:
        self.text.config(font=('courier', 12, 'normal'), background='black', fg='green')

    else:
        self.text.config(font=('courier', 12, 'normal'))

    index = not index

但是,在运行代码时,它始终处于夜间模式并且切换不起作用。帮助。源代码:http: //ideone.com/IVJuxX

原文由 Potato_head 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

background 和 fg 仅在 if 子句中设置。您还需要在 else 子句中设置它们:

 def onNightMode(self):
    if index:
        self.text.config(font=('courier', 12, 'normal'), background='black', fg='green')

    else:
        self.text.config(font=('courier', 12, 'normal'))

    index = not index


IE,

 else:
    self.text.config(font=('courier', 12, 'normal'), background='green', fg='black')

原文由 unutbu 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以导入 tkinter 库(Python 2.7 使用大写字母):

 import Tkinter

创建 tkinter 对象…

 root = tk.Tk()

…和 tkinter 按钮

toggle_btn = tk.Button(text="Toggle", width=12, relief="raised")
toggle_btn.pack(pady=5)
root.mainloop()

现在创建一个名为“切换”的新命令按钮,以便在按下浮雕属性(凹陷或凸起)时创建“切换”效果:

 def toggle():

    if toggle_btn.config('relief')[-1] == 'sunken':
        toggle_btn.config(relief="raised")
    else:
        toggle_btn.config(relief="sunken")

最后在您的按钮上应用此行为:

 toggle_btn = tk.Button(text="Toggle", width=12, relief="raised", command=toggle)

原文由 Albe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题