如何将此代码放入gui?我尝试将其添加到按钮中,但失败了!
我希望所有def say_hi(self)
都在gui中,而不是将其打印到shell中,而且打印输出在控制台中效果最好,而不是python shell!
import sys
import time
from random import randint
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
# self.roll is the button
def create_widgets(self):
self.roll = tk.Button(self)
self.roll["text"] = "rolldice"
self.roll["command"] = self.say_hi
self.roll.pack(side="left")
#self.quit is the kill button
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="right")
self.label = tk.Label(self, text='ROLL THE DICE !')
self.label.pack()
# this is my loading result.
def say_hi(self):
d = 0
for x in range(0,7):
for x in range (0,5):
b = "Loading" + "." * x
a = " "
print (b, end="\r")
time.sleep(0.1)
print (a, end="\r")
time.sleep(0)
print("finished rolling!")
time.sleep(2)
for x in range(0,7):
for x in range (0,5):
b = "printing" + "." * x
a = " "
print (b, end="\r")
time.sleep(0.1)
print (a, end="\r")
time.sleep(0)
print ("printed")
print ("here it is thankyou for using us!")
print (" ")
value = randint(1, 6)
self.label['text'] = value
self.label.pack()
root = tk.Tk()
app = Application(master=root)
app.mainloop()
答案 0 :(得分:1)
您可以使用Lable
和StringVar
。
Label小部件是标准的Tkinter小部件,用于在屏幕上显示文本或图像。标签只能显示单一字体的文本,但是文本可能会跨越多行。另外,可以在其中一个字符下划线,例如,以标记键盘快捷键。
这里check it out!的使用方法很好。
修改
如果您希望用户能够显示用户可以就地操作的数据,则使用Canvas小部件可能会更容易。
希望这会有所帮助!
答案 1 :(得分:1)
尝试一下。代替打印
self.label['text'] = b
self.label.pack()
root.update()
它更新在小部件内部打印的值。
import sys
import time
from random import randint
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
# self.roll is the button
def create_widgets(self):
self.roll = tk.Button(self)
self.roll["text"] = "rolldice"
self.roll["command"] = self.say_hi
self.roll.pack(side="left")
#self.quit is the kill button
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="right")
self.label = tk.Label(self, text='ROLL THE DICE !', padx=20)
self.label.pack()
# this is my loading result.
def say_hi(self):
d = 0
for x in range(0,7):
for x in range (0,5):
b = "Loading" + "." * x
a = " "
#self.label.pack_forget()
self.label['text'] = b
self.label.pack()
#root.update_idletasks()
root.update()
print (b, end="\r")
time.sleep(0.2)
print (a, end="\r")
time.sleep(0)
print("finished rolling!")
for x in range(0,7):
for x in range (0,5):
b = "Printing" + "." * x
a = " "
#self.label.pack_forget()
self.label['text'] = b
self.label.pack()
#root.update_idletasks()
root.update()
print (b, end="\r")
time.sleep(0.2)
print (a, end="\r")
time.sleep(0)
print ("printed")
print ("here it is thankyou for using us!")
print (" ")
value = randint(1, 6)
self.label['text'] = value
self.label.pack()
root = tk.Tk()
app = Application(master=root)
app.mainloop()