Python Tkinter 在一个变量中定义的循环条目 x 次运行

阿尔伯特

我想使用定义网络数量的 Tkinter 创建一个 Python 脚本,并使用用户在输入字段中插入的值,在下一页中创建 x 次网络来定义。然后用户插入的值来创建一个具有如下模式的文件:

--- #
networks:
- { cloud: cloud1, network:  }
- { cloud: cloud1, network:  }
- { cloud: cloud1, network:  }
- { cloud: cloud1, network:  }
...

例子:

如果用户在“定义网络数量”页面上输入 20,那么我们应该在“定义网络”页面中有 20 个输入字段,在文件中应该有 20 行,如下所示: - { cloud: cloud1, network: }

@AXK 帮助我完成了这项工作,非常感谢。例如,当我有10多个网络要介绍时,我也想有一个卷轴。我已经尝试在 AXK 代码上进行如下更改:

import Tkinter as tk
import tkFont as tkfont
import sys
from Tkinter import *

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(
            family="Helvetica", size=18, weight="bold", slant="italic"
        )
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.container = container
        self.current_frame = None

        self.num_networks = tk.IntVar()  # Var shared between pages
        self.show_frame("StartPage")

    def show_frame(self, page_name):
        """Show a frame for the given page name"""
        if self.current_frame:
            self.current_frame.destroy()
            self.current_frame = None

        frame_class = globals()[page_name]  # Ugly, but works.
        frame = frame_class(parent=self.container, controller=self)
        frame.grid(row=0, column=0, sticky="nsew")
        frame.tkraise()
        self.current_frame = frame


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self,text="This is the start page",font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self,text="Define the number of networks",command=lambda: controller.show_frame("PageOne"))
        button1.pack()


class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self,text="Define the number of networks",font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        nwnum = tk.Entry(self, textvariable=controller.num_networks)
        nwnum.pack()

        button1 = tk.Button(self,text="Go to the start page",command=lambda: controller.show_frame("StartPage"),)
        button1.pack()

        button2 = tk.Button(self,text="Define the networks",command=lambda: controller.show_frame("PageTwo"),)
        button2.pack()


class PageTwo(tk.Frame):
    def getent1(self):
      with open("/home/dante/output.txt", "w") as f:
        f.write("--- #" + "\n")
        f.write("networks:" + "\n")
        for entvar in self.entry_vars:
            value = entvar.get()
            if value:
                f.write("- { cloud: cloud1, network: "+ value+ " }"+ "\n")

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.scrollbar = Scrollbar(self, orient='vertical')
        label = tk.Label(self,text="Define the networks",font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        self.entries = []
        self.entry_vars = []

        self.scrollbar.config(command=self.yview)
        self.scrollbar.pack(side='right', fill='y')
        for t in range(1, self.controller.num_networks.get()+1):
            entvar = tk.StringVar()
            ent = tk.Entry(self, textvariable=entvar)
            self.entry_vars.append(entvar)
            self.entries.append(ent)
            ent.pack()
        button3 = tk.Button(self,text="Go to the start page",command=lambda: controller.show_frame("StartPage"),)
        button3.pack()
        button4 = tk.Button(self, text="Create the networks", command=self.getent1)
        button4.pack()

    def yview(self, *args):
        self.entry_vars.yview(*args)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

当我运行它时,我看到选项卡右侧的滚动条,但是当我向下或向上按下时,出现以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "program.py", line 96, in yview
    self.entry_vars.yview(*args)
AttributeError: 'list' object has no attribute 'yview'

我怎样才能做到这一点?

PS我对编程很陌生

AKX

我重构了一些东西:

  • 我更改了导入以使用我的 Python 3 安装。对你来说,情况可能会有所不同。
  • YAML 输出被写入sys.stdout,而不是文件,因为我没有/home/dante. ;)
  • 框架对象现在不会立即全部初始化;相反,它们仅在show_frame被调用时创建
  • 保存网络数量的 Tk 变量现在归controller; 子帧从那里写入/读取它。
  • 保存第 3 帧网络名称的字符串变量存放在第三帧的列表中,并在 YAML 写入函数中从那里读取。

import tkinter as tk
from tkinter import font as tkfont
import sys


class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(
            family="Helvetica", size=18, weight="bold", slant="italic"
        )
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.container = container
        self.current_frame = None

        self.num_networks = tk.IntVar()  # Var shared between pages
        self.show_frame("StartPage")

    def show_frame(self, page_name):
        """Show a frame for the given page name"""
        if self.current_frame:
            self.current_frame.destroy()
            self.current_frame = None

        frame_class = globals()[page_name]  # Ugly, but works.
        frame = frame_class(parent=self.container, controller=self)
        frame.grid(row=0, column=0, sticky="nsew")
        frame.tkraise()
        self.current_frame = frame


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(
            self,
            text="This is the start page",
            font=controller.title_font,
        )
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(
            self,
            text="Define the number of networks",
            command=lambda: controller.show_frame("PageOne"),
        )
        button1.pack()


class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(
            self,
            text="Define the number of networks",
            font=controller.title_font,
        )
        label.pack(side="top", fill="x", pady=10)

        nwnum = tk.Entry(self, textvariable=controller.num_networks)
        nwnum.pack()

        button1 = tk.Button(
            self,
            text="Go to the start page",
            command=lambda: controller.show_frame("StartPage"),
        )
        button1.pack()

        button2 = tk.Button(
            self,
            text="Define the networks",
            command=lambda: controller.show_frame("PageTwo"),
        )
        button2.pack()


class PageTwo(tk.Frame):
    def getent1(self):
        f = sys.stdout
        f.write("--- #" + "\n")
        f.write("networks:" + "\n")
        for entvar in self.entry_vars:
            value = entvar.get()
            if value:
                f.write(
                    "- { cloud: cloud1, network: "
                    + value
                    + " }"
                    + "\n"
                )

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        label = tk.Label(
            self,
            text="Define the networks",
            font=controller.title_font,
        )
        label.pack(side="top", fill="x", pady=10)
        self.entries = []
        self.entry_vars = []

        for t in range(1, self.controller.num_networks.get()):
            entvar = tk.StringVar()
            ent = tk.Entry(self, textvariable=entvar)
            self.entry_vars.append(entvar)
            self.entries.append(ent)
            ent.pack()
        button3 = tk.Button(
            self,
            text="Go to the start page",
            command=lambda: controller.show_frame("StartPage"),
        )
        button3.pack()
        button4 = tk.Button(
            self, text="Create the networks", command=self.getent1
        )
        button4.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 python tkinter 中,我想让一个按钮消失并运行一个定义

每X秒运行一次Python脚本

如何使Tkinter python脚本每X秒获取一次变量?

在python中每x秒运行一次循环以废弃网站

获得一个while循环,以在PHP中使用两个条件运行“ X”次

在python中简明一个for循环(x for x in ...)

Python Tkinter,每秒更新一次

在for循环中每x次运行Async

for循环仅运行一次(python)

我想每x秒在一个线程python中运行一个函数

一次运行后,Tkinter窗口自动关闭

在Python中运行for循环:第一次正常运行,但其余运行未正常运行

连续运行脚本 X 次的推荐方法是什么(一次一个)

在python for循环中一次运行3个变量。

Python 3.x多处理tkinter主循环

更新Tkinter的标签,而另一个循环运行

for循环在Python 3中运行一次

如何在python中仅运行一次循环?

使用CheckButtons修改python 3x在tkinter中的功能

如何在python中制作一个循环x,将值赋给变量并每次打印该值?

使功能第一次使用Tkinter单击后只能运行一次吗?

在 Python 中安排一个简单的通知脚本每小时运行一次

Python 3,Tkinter和线程化一个长期运行的过程,OOP风格

使用Tkinter窗口运行另一个显示摄像机预览的python文件

Python / tkinter:一次执行一个命令即可更改标签两次

在Tkinter中运行无限循环时如何使用关闭(X)或任何其他按钮

我的 Tkinter 按钮命令只在循环中运行一次

Python Tkinter after()仅执行一次

Python:Tkinter bind("<<Modified>>") 只工作一次