我一直在使用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
答案 0 :(得分:2)
您可以导入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"的新命令按钮。为了创造"切换"的效果当您按下浮雕属性(凹陷或凸起)时:
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)
答案 1 :(得分:1)
后台和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
即,
else:
self.text.config(font=('courier', 12, 'normal'), background='green', fg='black')
答案 2 :(得分:1)
这是一个代码段,如果您愿意的话,它将帮助您使用切换按钮动画。当然,您只需要单击即可添加要执行的功能,这取决于您。
'''
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()