我一直在做一个井字游戏项目,我打算创建9个按钮小部件,每个小部件都有一张图片。我想移动他们,所以他们将在一条线上连续3次。 这是我的代码:
#imports:
from Tkinter import *
from PIL import ImageTk, Image
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#constants
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#classes:
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
myapp = App()
class GUI:
def __init__(self):
self.myapp = myapp
self.myapp.master.title("tkname")
self.myapp.master.maxsize(2000, 1200)
def create_and_pack_canvas(self, game_board_height, game_board_width):
canvas = Canvas(height = game_board_height, width = game_board_width)
canvas.pack(expand=1, fill=BOTH)
return canvas
def form_game_board(self):
x = 404
y = 150
canvas = self.create_and_pack_canvas(1000, 1000)
for i in range(3):
for j in range(3):
btn = gameButton("")
btn.create_and_pack(canvas, x, y)
x += 200
x = 404
y += 208
self.myapp.mainloop()
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class gameButton:
def __init__(self, picture_param):
self.picture = ImageTk.PhotoImage(Image.open("somepic"))
self.picture_height = self.picture.height()
self.picture_width = self.picture.width()
def callback(self):
print 10
def create_and_pack(self, canvas, x_pixels, y_pixels):
self.b = Button(myapp, text="Print 10~", command = self.callback, image = self.picture)
self.b.pack()
#self.b.place(bordermode = OUTSIDE, x = x_pixels, y = y_pixels)
def __str__(self):
pass
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#main
def main():
gui = GUI()
gui.form_game_board()
if __name__ == "__main__":
main()
请注意这一行:
#self.b.place(bordermode = OUTSIDE, x = x_pixels, y = y_pixels)
在代码中,我把它作为一个注释,它基本上是应该移动按钮的行。如果你运行代码,它只会将所有按钮一个接一个地放在另一行中,其中9个。 在self.b.place()行之后,它们都消失了。 也许他们搬到了某个地方太远,也许没有,但我认为这个地方()不起作用,而且我很难找出原因。
提前致谢。