tkinter,除非添加了某些功能,否则图片不会显示

时间:2019-05-14 03:17:17

标签: python 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

1 个答案:

答案 0 :(得分:0)

您正在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()