Tkinter应该位于单独的python文件中,或者可以位于同一代码中?

时间:2018-10-05 10:49:36

标签: python-3.x selenium-webdriver tkinter

Coordinate_1_X = input (" Enter Coordinate point 01 _ X:   ")
Coordinate_1_Y = input (" Enter Coordinate point 01 _ Y:   ")

Coordinate_2_X = input (" Enter Coordinate point 02 _ X:   ")
Coordinate_2_Y = input (" Enter Coordinate point 02 _ Y:   ")

Coordinate_3_X = input (" Enter Coordinate point 03 _ X:   ")
Coordinate_3_Y = input (" Enter Coordinate point 03 _ Y:   ")

Coordinate_4_X = input (" Enter Coordinate point 04 _ X:   ")
Coordinate_4_Y = input (" Enter Coordinate point 04 _ Y:   ")

上面的数据对于启动我的webdriver selenium应用程序是必不可少的,一旦我添加了input_4,代码就会启动。

我的第一个问题是(如果我想使用Tkinter允许最终用户在GUI中添加此信息,我是否必须在另一个Python文件中创建Tkinter代码?)

如果该问题的答案是(不,您可以在同一主应用程序代码中添加Tkinter代码),那么我有第二个问题,如下所示... (单击Tkinter代码中的“提交”按钮后,如何让代码运行?)

1 个答案:

答案 0 :(得分:1)

这是一个简单的示例,向您展示如何在GUI上从用户那里获取输入,然后使用函数/方法对其进行一些操作。

import tkinter as tk

class Example(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        tk.Label(self, text=" Enter Coordinate point 01 _ X:   ").grid(row=0, column=0)
        self.entry1 = tk.Entry() # this is the widget the user can type in
        self.entry1.grid(row=0, column=1)

        tk.Label(self, text=" Enter Coordinate point 01 _ Y:   ").grid(row=1, column=0)
        self.entry2 = tk.Entry()
        self.entry2.grid(row=1, column=1)
        # This button will run the function that creates a new window with the user input
        tk.Button(self, text="Do something", command=self.do_something).grid(row=2, column=0, pady=5)

    def do_something(self):
        top = tk.Toplevel(self)

        x = self.entry1.get() # the get() method will grab a string of the content of the entry widget
        y = self.entry2.get()

        tk.Label(top, text="You provided coords for point 01 X: {} and Y: {}!".format(x, y)).grid(row=0, column=0)

if __name__ == "__main__":
    Example().mainloop()

结果:

enter image description here

按下按钮后:

enter image description here