尝试制作两个窗口。一个用于显示随机图像,另一个用于改变为新的随机图像的按钮。目前,如果我在Display.update_image()中放置一个计时器并在Display.__init__
中调用它,我可以让它定期更换图片。
但是将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()
答案 0 :(得分:0)
正如jasonharper在上述评论中指出的那样。
问题来自这一行:
self.random_100_button = tk.Button(text = 'Random from top 100', width = 50, command = self.app.update_image())
如果您将属性command
设置为等于self.app.update_image()
,则表示您正在执行该功能,并将None
的值分配给command
。
从声明中删除括号()
应解决问题,因为您将函数本身赋值为command
而不是函数的返回值。