【问题标题】:How to create a tkinter toggle button?如何创建一个 tkinter 切换按钮?
【发布时间】:2014-06-02 20:32:54
【问题描述】:

我一直在使用 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

【问题讨论】:

    标签: python tkinter toggle python-2.x


    【解决方案1】:

    您可以导入 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()
    

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

    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)
    

    【讨论】:

    • 您的代码格式不正确。此外,仅代码的答案通常不如代码加上解释那么好。你能解释一下为什么你的代码解决了这个问题吗?
    • 我不太懂英语,但我很懂 python: 你是什么意思 formatted propely?对于 Python 2.7 工作正常!!!!将其复制并粘贴到文本文件中并将其另存为 .py!在给一个坏的 cmets 之前测试!!!
    • 在我写评论时,toggle 的正文与def 语句的缩进相同,您可以复制和粘贴它。查看编辑历史,您会看到您的原始版本已被其他人编辑以修复缩进。
    • 这不是负面评论,我只是在陈述一个事实。我不想编辑答案,因为我认为您可能不知道如何正确格式化它(因为它最初是错误的),并且通过让您修复它,您将学习如何格式化您的答案。如果你被冒犯了,我很抱歉。我唯一的目的是帮助您写出更好的答案。
    • 如果您编辑此答案会比提供具有相同信息的另一个答案更好。
    【解决方案2】:

    仅在 if 子句中设置背景和 fg。您还需要在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
    

    即,

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

    【讨论】:

    • UnboundLocalError 是由于对index 的赋值,当您真的希望它引用全局变量时,默认情况下它使其成为局部变量。快速解决方法是在函数内添加语句global index。但更好的解决方法是避免使用可变全局变量,而是将 index 设为实例属性 self.index
    【解决方案3】:

    如果您愿意,这里有一个代码 sn-p 可以帮助您制作切换按钮动画。当然,你只需要添加你想要在点击时执行的功能,这取决于你。

    '''
        import tkinter as tk
    
        # --- functions ---
    
        def move(steps=10, distance=0.1):
            if steps > 0:
                # get current position
                relx = float(frame.place_info()['relx'])
    
                # set new position
                frame.place_configure(relx=relx+distance)
    
                # repeate it after 10ms
                root.after(10, move, steps-1, distance)
    
        def toggle(event):
            if button["text"] == "Yes":
                move(25, 0.02)  # 50*0.02 = 1
                button["text"] = "No"
                print("Clicked on yes")
            elif button["text"] == "No":
                move(25, -0.02)
                button["text"] = "Yes"
                print("Clicked on no")
    
    
        # --- main --
    
        root = tk.Tk()
    
        frame = tk.Frame(root, background='red')
        frame.place(relx=0, rely=0, relwidth=0.5, relheight=1)
    
        # to center label and button
        #frame.grid_columnconfigure(0, weight=1)
        #frame.grid_rowconfigure(0, weight=1)
        #frame.grid_rowconfigure(3, weight=1)
    
    
    
    
        button = tk.Button(frame, text='Yes',width=5,height=1)
        button.place(relx=0.25,rely=0.5,relwidth=0.5, relheight=0.1)
        button.bind("<Button-1>",toggle)
    
    
        root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2022-11-28
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 2016-04-04
      • 2013-12-27
      • 1970-01-01
      相关资源
      最近更新 更多