python|实现tkinter对话框输入打印输出

本博文源于python基础,实验由Toplevel组件来创建自定义的对话框。

实验效果

在这里插入图片描述
在这里插入图片描述

实验原理

设计一个自定义的对话框MyDialog与MyButton类,然后实例化加入主窗口

实验代码

# -*- coding:utf-8 -*-
#
import tkinter
import tkinter.messagebox


class MyDialog(object): #定义对话框类
    def __init__(self, root): #对话框初始化
        self.top = tkinter.Toplevel(root) #生成TopLevel组件
        label = tkinter.Label(self.top, text='PLease Input') # 生成标签组件
        label.pack()
        self.entry = tkinter.Entry(self.top) # 生成文本框组件
        self.entry.pack()
        self.entry.focus() # 文本框获得焦点
        button = tkinter.Button(self.top, text='Ok', command=self.Ok)  #生成按钮,设置按钮处理函数
        button.pack()

    def Ok(self): # 定义按钮事件处理函数
        self.input = self.entry.get()  # 获取文本框中的内容,保存为input
        self.top.destroy() #销毁对话框

    def get(self): # 返回在文本框中内容
        return self.input


class MyButton(object):
    def __init__(self, root, type):
        self.root = root # 保持父窗口引用
        if type == 0: # 类不同创建不同按钮
            self.button = tkinter.Button(root, text='Create', command=self.Create)
        else:
            self.button = tkinter.Button(root, text='Quit', command=self.Quit)
        self.button.pack()

    def Create(self):
        d = MyDialog(self.root) # 生成一个对话框
        self.button.wait_window(d.top) # 等待对话框结束
        tkinter.messagebox.showinfo('Python', 'You input:\n' + d.get()) # 输出输入值,重点语句

    def Quit(self): # 退出主窗口
        self.root.quit()


root = tkinter.Tk()
MyButton(root, 0)
MyButton(root, 1)

root.mainloop()

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值