-1
尝试制作两个窗口。一个显示一个随机图像,另一个显示一个按钮,它变成一个新的随机图像。目前,如果我在Display.update_image()中放置一个定时器并在Display.__init__
中调用它,我可以定期更改它的图片。Tkinter从父母改变子窗口
但将update_image()
命令放在父窗口的按钮上不起作用。是否有可能从第一个窗口改变第二个窗口?
import tkinter as tk
from PIL import Image, ImageTk
import random
def top_100():
"""
Returns a list of the top 100 biggest NZ cities.
"""
file = open("Top100NZcities.csv")
cities = file.readlines()
return [city.strip() for city in cities]
class UserInt():
def __init__(self):
self.root = tk.Tk()
self.newWindow = tk.Toplevel(self.root)
self.app = Display(self.newWindow)
self.random_100_button = tk.Button(text = 'Random from top 100',
width = 50,
command = self.app.update_image())
self.random_100_button.pack()
self.root.mainloop()
class Display():
def __init__(self, master):
self.root = master
#Get the list of cities,.
self.cities = top_100()
#Set to fullscreen.
w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
self.root.overrideredirect(1)
self.root.geometry("%dx%d+0+0" % (w, h))
#Display initial image.
self.image_init = ImageTk.PhotoImage(Image.open("black_background.jpg"))
self.panel = tk.Label(self.root, image=self.image_init)
self.display = self.image_init
self.panel.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
def update_image(self):
"""
Replaces the screen's current image with a new random image.
"""
self.city = random.choice(self.cities)
self.image_rand = Image.open("NZ maps/{}_nz.png".format(self.city))
#Rescale image to fit window.
w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
self.scale_factor = h/self.image_rand.height
self.scaled_image = self.image_rand.resize(
(int(self.scale_factor * self.image_rand.width), h), Image.ANTIALIAS
)
self.image_display = ImageTk.PhotoImage(self.scaled_image)
self.panel.configure(image=self.image_display)
print(self.city)
self.display = self.image_display
def main():
app = UserInt()
if __name__ == '__main__':
main()
“不起作用”是什么意思?程序崩溃了吗?你有错误吗?它显示错误的图像吗?图像是否出现在错误的地方? ... –
'command = self.app.update_image()'意味着调用'update_image()'RIGHT NOW,并将其返回值(无)作为单击按钮时要执行的函数保存。摆脱括号,所以你传递的是实际的功能,而不是结果。 – jasonharper
你应该通过'command'传递一个函数。 – Goyo