首页 > 解决方案 > tkinter,除非添加了某些功能,否则图像不会显示

问题描述

我已经为基本游戏编写了代码,但图像和形状不会显示,除非我添加类似 item.pack() 或 win.mainloop() [这实际上没有意义],然后是它下面的行不要跑。

当我什么都没有时,按钮会显示,但图像不会显示。

import tkinter as tk
import random
from tkinter import messagebox

win = tk.Tk()

my_label = tk.Label(win, text="Color of the Baloon Game")
my_label.pack()

my_canvas = tk.Canvas(win, width=400, height=600)
my_canvas.pack()

background_image=tk.PhotoImage(file = "CS_Game_menu.png")
background_label = tk.Label(my_canvas, image=background_image)
background_label.photo = background_image
background_label.grid(row = 0, rowspan = 10, column = 0, columnspan = 10)


def drawCircle():
    color = "green"
    x1 = 265
    y1 = 80
    diameter = 90
    my_canvas.destroy()
    circle_button.destroy()
    quit_button.destroy()
    my_label.destroy()
    my_label1 = tk.Label(win, text="What is the Color of the Baloon?", font="Purisa")
    my_label1.pack()
    my_canvas1 = tk.Canvas(win, width=400, height=600)
    my_canvas1.pack()
    image1 = r"CS_Game_baloon.png"
    photo1 = tk.PhotoImage(file=image1)
    item = my_canvas1.create_image(200, 350, image=photo1)
    shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
    item.pack()
    game1_button = tk.Button(my_canvas1, text = "Green")
    game1_button.grid(row= 8, column = 3)
    game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
    game2_button = tk.Button(my_canvas1, text = "Blue")
    game2_button.grid(row= 8, column = 5)
    game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
    game3_button = tk.Button(my_canvas1, text = "Red")
    game3_button.grid(row= 8, column = 7)
    game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")


circle_button = tk.Button(win, text="New Game")
circle_button.pack()
circle_button["command"] = drawCircle

quit_button = tk.Button(win, text="Quit")
quit_button.pack()
quit_button['command'] = win.destroy

标签: pythontkinter

解决方案


您正在使用对象上的create_...方法和grid方法canvas。它不会像您预期的那样运行。

为了实现你想要的,你可以创建一个Frame,把你的按钮放在里面,然后create_window在你的画布上使用方法:

def drawCircle():
    ...
    shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
    frame = tk.Frame(my_canvas1)
    game1_button = tk.Button(frame, text = "Green")
    game1_button.grid(row= 8, column = 3)
    game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
    game2_button = tk.Button(frame, text = "Blue")
    game2_button.grid(row= 8, column = 5)
    game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
    game3_button = tk.Button(frame, text = "Red")
    game3_button.grid(row= 8, column = 7)
    game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")
    my_canvas1.create_window(200,500,window=frame)

当然,win.mainloop()如果您还没有添加到程序的底部,请添加。


推荐阅读