如何在东侧插入按钮,在东侧插入图像文件,或者仅使用Tk作为背景插入按钮

时间:2018-02-16 18:53:00

标签: python-2.7 canvas tkinter

这是我的剧本

# Python 2.7.14 version

from Tkinter import *
import Tkinter
import tkMessageBox
from urllib2 import urlopen
import PIL
from PIL import ImageTk
import ImageTk

FILENAME = 'Fleur_de_lys.jpg'
root = Tk()
background = Canvas(root, width=250, height=250)##AttributeError: class Tk has no attribute 'Canvas'
canvas.pack()
tk_img = ImageTk.PhotoImage( file = FILENAME)
canvas.create_image(125, 125, image=tk_img)
quit_button = tk.Button(root, text = "Quit", command = root.quit, anchor = 'w',
                    width = 10, activebackground = "#33B5E5")
quit_button_window = canvas.create_window(10, 10, anchor='nw', window=quit_button)
root.mainloop()

无论我做什么尝试,我都会继续获得AttributeError:类Tk没有属性'Canvas'如果我只是创建按钮,我的错误在哪里我没有任何问题所有工作但是当我尝试拥有背景图像时不起作用

2 个答案:

答案 0 :(得分:0)

问题似乎是您正在创建一个画布,并将其存储在一个名为background的变量中,但是您尝试调用的最后一行是' canvas&#39 ;,你从未创造过的。

改变这个:

background = Canvas(root, width=250, height=250)
canvas.pack()
...
canvas.create_image(125, 125, image=tk_img)

到此:

background = Canvas(root, width=250, height=250)
background.pack()
...
background.create_image(125, 125, image=tk_img)

答案 1 :(得分:0)

我修复了问题jpg图像未被接受我用gif制作了它。还找到了如何纠正按钮位置和位置。

Here is the example without all the program

canvas = Canvas(root, width = 500, height = 500, bg='black')
canvas.pack(expand=YES, fill=BOTH)
my_image =  PhotoImage(file='C:\\MOTD\\fleur_de_lys.gif')
canvas.create_image(0, 0, anchor = NW, image=my_image)

b1 = Button(root, text="From the Commander", command=callback,anchor = 'w',
            width = 18, activebackground = "#33B5E5")
button_window1 = canvas.create_window(10, 10, anchor='nw', window=b1)