我是python的新手,所以我试图制作一个GUI,因为我必须在特定位置放置一个按钮。
我尝试使用self.nxt_form.place(x=200,y=100)
代替self.nxt_form.pack()
。
但按钮消失了,只有框架出现时才出现。你能告诉我如何把按钮放在特定的位置吗?
以下是代码:
import tkinter as tk
class Main_form:
def __init__(self, root,title="Simulated MTBF"):
self.root = root
self.frame = tk.Frame(self.root)
"""Button nxt_form which moves to next form"""
self.nxt_form = tk.Button(self.frame, text = 'Next Form', width = 25,command = self.new_window)
self.nxt_form.pack()
self.frame.pack()
"""command to open new window by clicking Button """
def new_window(self):
self.newWindow = tk.Toplevel(self.root)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, root):
self.root = root
self.frame = tk.Frame(self.root)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.root.destroy()
def main():
root = tk.Tk()
app = Main_form(root)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:1)
当我使用tkinter时,我使用了列和行来定位对象
self.btn = tk.Button(self, text = "button")
self.btn.grid(row = 1, column = 1)
EDIT - 针对评论(见下文)扩展了信息
我会做一个标签并改变它的宽度和高度来制作你需要的间距(注意我也是python的初学者,所以这可能是一个糟糕的方式,但它有效)
from tkinter import *
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar
class MainMenu(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(MainMenu, self).__init__(master)
self.grid()
self.create_GUI()
def create_GUI(self):
frame1 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5)
frame1.grid(row=0, column=0, columnspan=3, padx=8)
#the frame is not needed but it is a good thing to use as can group
#parts of your interface together
self.text1 = Entry(frame1)
#note if you were not using frames would just put self here
self.text1.grid(row = 1, column = 0)
self.text2 = Label(frame1, text = "",height = 10)
self.text2.grid(row = 2 , column = 0)
self.text3 = Entry(frame1)
self.text3.grid(row = 3, column = 0)
root = Tk()
root.title("hi")
root.geometry("500x500")
root.configure(bg="white")
app = MainMenu(root)
root.mainloop()
另请注意,您不能将pack和grid一起使用,您可以做的是将对象分组到不同的帧中,然后在一个帧中使用网格并打包在不同的帧中。我个人更喜欢使用网格打包,因为它可以让你更好地控制你的对象然后打包