有关Python的图形化界面——tkinter

文档:

https://docs.python.org/zh-cn/3/library/tkinter.html

https://wiki.python.org/moin/TkInter

文档中的代码:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

执行结果(我给拉大了一点)

点QUIT就退出界面了

点”Hello World(click me)“会输出:hi there, everyone!

 

参考:https://www.runoob.com/python/python-gui-tkinter.html

属性描述
Dimension控件大小;
Color控件颜色;
Font控件字体;
Anchor锚点;
Relief控件样式;
Bitmap位图;
Cursor光标;
控件描述
Button按钮控件;在程序中显示按钮。
Canvas画布控件;显示图形元素如线条或文本
Checkbutton多选框控件;用于在程序中提供多项选择框
Entry输入控件;用于显示简单的文本内容
Frame框架控件;在屏幕上显示一个矩形区域,多用来作为容器
Label标签控件;可以显示文本和位图
Listbox列表框控件;在Listbox窗口小部件是用来显示一个字符串列表给用户
Menubutton菜单按钮控件,用于显示菜单项。
Menu菜单控件;显示菜单栏,下拉菜单和弹出菜单
Message消息控件;用来显示多行文本,与label比较类似
Radiobutton单选按钮控件;显示一个单选的按钮状态
Scale范围控件;显示一个数值刻度,为输出限定范围的数字区间
Scrollbar滚动条控件,当内容超过可视化区域时使用,如列表框。.
Text文本控件;用于显示多行文本
Toplevel容器控件;用来提供一个单独的对话框,和Frame比较类似
Spinbox输入控件;与Entry类似,但是可以指定输入范围值
PanedWindowPanedWindow是一个窗口布局管理的插件,可以包含一个或者多个子控件。
LabelFramelabelframe 是一个简单的容器控件。常用与复杂的窗口布局。
tkMessageBox用于显示你应用程序的消息框。

 

打开图片

参考:

https://zhuanlan.zhihu.com/p/75872830?from_voters_page=true

https://blog.csdn.net/u010921682/article/details/89848375?utm_term=tkinter%E6%89%93%E5%BC%80%E5%9B%BE%E7%89%87&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-2-89848375&spm=3001.4430

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")
def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file

file = clicked()
filePosition = file[0]

img = Image.open(filePosition)  # 打开图片
photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

window.mainloop()

执行结果:



灰度图像

参考:https://www.jb51.net/article/173339.htm

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")
def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file

file = clicked()
filePosition = file[0]

img = Image.open(filePosition)  # 打开图片
img = img.convert('L')

photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

window.mainloop()

结果:

如果两张图片一起显示:

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")
def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file

file = clicked()
filePosition = file[0]

img = Image.open(filePosition)  # 打开图片
Img = img.convert('L')

photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

photo1 = ImageTk.PhotoImage(Img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo1)
imglabel.grid(row=0, column=3, columnspan=3)

window.mainloop()

结果:

 

图片缩放

参考:

https://blog.csdn.net/guduruyu/article/details/70842142?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-2.control&dist_request_id=1328730.856.16167419643941449&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-2.control

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()
window.title("Open picture")
def clicked():
    file = filedialog.askopenfilenames(initialdir=os.path.dirname(os.path.abspath(__file__)))
    return file

file = clicked()
filePosition = file[0]

img = Image.open(filePosition)  # 打开图片
img = img.resize((256,128))
Img = img.convert('L')
Img = Img.resize((256,128))
photo = ImageTk.PhotoImage(img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo)
imglabel.grid(row=0, column=0, columnspan=3)

photo1 = ImageTk.PhotoImage(Img)  # 用PIL模块的PhotoImage打开
imglabel = Label(window, image=photo1)
imglabel.grid(row=0, column=3, columnspan=3)

window.mainloop()

结果:

 

 

 

 

 

 

________________________________________________________________________

题外话,刚刚实操了一下加噪声(多亏我之前弯路走的足够多,现在连新模块都不用安装了,泪目)

照抄:https://blog.csdn.net/qq_38395705/article/details/106311905

import cv2
import random
import numpy as np
from matplotlib import pyplot as plt

def gasuss_noise(image, mean=0, var=0.001):
    '''
        添加高斯噪声
        mean : 均值
        var : 方差
    '''

    image = np.array(image / 255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out * 255)

    return out


def sp_noise(image,prob):

    '''
    添加椒盐噪声
    prob:噪声比例
    '''

    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]

    return output

img = cv2.imread("starry-night.jpg")

# 添加椒盐噪声,噪声比例为 0.02
out1 = sp_noise(img, prob=0.02)

# 添加高斯噪声,均值为0,方差为0.01
out2 = gasuss_noise(img, mean=0, var=0.01)


# 显示图像
titles = ['Original Image', 'Add Salt and Pepper noise','Add Gaussian noise']
images = [img, out1, out2]

plt.figure(figsize = (20, 15))
for i in range(3):
    plt.subplot(1,3,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

结果:

 

 

另外,还有一个功能实现,见AttributeError: ‘Image‘ object has no attribute ‘shape‘

(打开文件之后,对文件进行加噪声的处理,再显示出来)

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python中,可以使用tkinter模块来创建界面。tkinterPython的内置GUI模块,可以快速地创建GUI应用程序。你可以使用以下代码来创建一个简单的窗口: ```python import tkinter win = tkinter.Tk() win.geometry("250x130") win.title("没有组件的窗体") win.mainloop() ``` 这段代码导入了tkinter模块,并使用Tk()方法创建了一个窗口对象。然后使用geometry()方法设置窗口大小,使用title()方法设置窗口名称。最后调用mainloop()方法进入消息循环,等待处理窗口事件。这样就创建了一个没有组件的窗体。\[1\] 如果你想在窗口中添加组件,比如标签、输入框和按钮,可以使用以下代码: ```python from tkinter import * top = Tk() labname = Label(top, text='账号', width=80) labpwd = Label(top, text='密码', width=80) entname = Entry(top, width=100) entpwd = Entry(top, width=100, show='*') but_ok = Button(top, text='登录', command=login) but_cancel = Button(top, text='重置', command=cancel) but_quit = Button(top, text='退出', command=_quit) ``` 这段代码中,我们首先导入了tkinter模块。然后使用Tk()方法创建了一个根窗口对象。接下来,我们使用Label()方法创建了两个标签,使用Entry()方法创建了两个输入框,使用Button()方法创建了三个按钮。你可以根据需要自定义标签的文本、输入框的宽度和按钮的文本和命令。最后,调用mainloop()方法进入等待处理窗口事件的状态。\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [Pythontkinter图形界面设计学习二](https://blog.csdn.net/qq_32393893/article/details/128007479)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python GUI 设计(一)———Tkinter窗口创建、组件布局](https://blog.csdn.net/lyx4949/article/details/123137002)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值