[英]How can I make an infinity cycle creating buttons (tkinter)?
我想創建按鈕,如果按下它 - 創建一個新的但依此類推(基本上是無限循環)。 但它只工作一次 - 只創建一個額外的按鈕。
from tkinter import *
class Application(Frame):
rw = 0
cl = 0
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.btn1 = Button(self, text = 'Create a new button')
self.btn1.grid(row = 0, column = 0, sticky = W)
self.btn1['command'] = self.new_button
def new_button(self):
rw = 1
cl = 1
self.btn1 = Button(self, text = 'Create a new button')
self.btn1.grid(row = rw, column = cl, sticky = W)
rw+=1
cl+=1
root = Tk()
root.title('King of the Kings!')
root.geometry('400x205')
app = Application(root)
root.mainloop()
干杯!
以下是您的代碼中的一些更改。 我創建了rw
和cl
實例變量,並刪除了rw = 1
和cl = 1
因為每次調用該函數時,它都會創建一個新按鈕,但將其直接放置在位置 (1, 1) 的第一個按鈕上方。
from tkinter import *
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.rw = 1 # Made rw and cl instance variables
self.cl = 1 #
self.grid()
self.create_widgets()
def create_widgets(self):
self.btn1 = Button(self, text = 'Create a new button')
self.btn1.grid(row = 0, column = 0, sticky = W)
self.btn1['command'] = self.new_button
def new_button(self):
self.btn1 = Button(self, text = 'Create a new button')
self.btn1.grid(row=self.rw, column=self.cl, sticky = W)
self.rw += 1
self.cl += 1
root = Tk()
root.title('King of the Kings!')
root.geometry('400x205')
app = Application(root)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.