如何通过按下按钮 kivy/kivymd/python 在另一个窗口中创建按钮
Posted
技术标签:
【中文标题】如何通过按下按钮 kivy/kivymd/python 在另一个窗口中创建按钮【英文标题】:How do i create a button in another window by pressing a button kivy/kivymd/python 【发布时间】:2021-06-10 11:41:20 【问题描述】:我正在尝试通过按下按钮来创建按钮,但我找不到任何有关它的信息。
【问题讨论】:
【参考方案1】:您可以在 kivy 或 kivyMD 中使用这种方法。
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.button import MDRaisedButton
from kivy.properties import ObjectProperty
KV = '''
ScreenManager:
id: screen_manager
Screen:
id: screenID
MDRaisedButton:
text: "Create Button"
pos_hint: 'center_x': .5, 'center_y': .5
on_release: app.createButton()
'''
class Example(MDApp):
screen_manager = ObjectProperty() # IMPORTANT!
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = Builder.load_string(KV)
def build(self):
return self.screen
def createButton(self):
print("button created")
self.btn = MDRaisedButton(text= "New Button", pos_hint= 'center_x': .5, 'center_y': .7)
self.root.ids.screenID.add_widget(self.btn)
Example().run()
【讨论】:
【参考方案2】:试试这个
from tkinter import *
import tkinter as tk
class MainWindow(tk.Frame):
counter = 0
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.button = tk.Button(self, text="Create new hotlink",
command=self.create_window)
self.button.pack(side="top")
def create_window(self):
self.counter += 1
t = tk.Toplevel(self)
t.wm_title("All the best to hackathon")
fields = 'Hotlink Name', 'URL'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
def button2():
newButton = tk.Button(root, text=fields[0])
newButton.pack(side=RIGHT)
ents = makeform(t, fields)
t.bind('<Return>', (lambda event, e=ents: fetch(e)))
b2 = Button(t, text='Save', command=button2)
b2.pack(side=LEFT, padx=5, pady=5)
if __name__ == "__main__":
root = tk.Tk()
main = MainWindow(root)
main.pack(side="top", fill="both", expand=True)
root.mainloop()
【讨论】:
以上是关于如何通过按下按钮 kivy/kivymd/python 在另一个窗口中创建按钮的主要内容,如果未能解决你的问题,请参考以下文章
如何通过按下按钮 kivy/kivymd/python 在另一个窗口中创建按钮
如何在按下并释放一次按钮时打开 LED,然后通过再次按下和释放将其关闭?