python - Tkinter - 使用绑定(bind)动态调整框架大小

标签 python python-3.x tkinter

我正在尝试创建一个 GUI 前端来使用 python tkinter 显示一些数据。

我有一个框架,它又具有其他小部件,例如按钮和列表框等。 每当光标放置在框架边框上时,我都会尝试动态增加/减少框架,就像我们在用户端的普通窗口上所做的那样。

enter image description here

我已经完成了相同的绑定(bind)功能。 但看起来我错过了一些东西。

  def left_click(event):
      tkinter.Label(Frame1, text = "Left Click!").pack()



  self.Frame1 = Frame(top)        
  self.Frame1.place(relx=0.01, rely=0.152, relheight=0.678 , relwidth=0.98)
  self.Frame1.configure(relief=GROOVE)
  self.Frame1.configure(borderwidth="10")
  self.Frame1.configure(relief=GROOVE)
  self.Frame1.configure(background="#D1C8E6")
  self.Frame1.configure(width=900)
  self.Frame1.configure(highlightthickness="4")
  self.Frame1.bind("<Button-1>", left_click)

我是 python tk inter 的新手。

最佳答案

您需要绑定(bind)以下鼠标事件来执行帧大小调整:

  • <ButtonPress-1> (按下鼠标左键)根据鼠标位置确定是否开始调整大小
  • <ButtonRelease-1> (释放鼠标左键)停止调整大小
  • <Motion> (鼠标在框架内移动)如果按下鼠标开始调整大小,则执行调整大小

下面是示例代码:

from tkinter import *

HORIZONTAL = 1
VERTICAL   = 2

class App:
    def __init__(self, top):
        self.Frame1 = Frame(top, bd=5, relief='raised', width=100, height=100)
        self.Frame1.place(x=10, y=10)
        self.Frame1.bind("<ButtonPress-1>", self.start_resize)
        self.Frame1.bind("<ButtonRelease-1>", self.stop_resize)
        self.Frame1.bind("<Motion>", self.resize_frame)
        self.resize_mode = 0
        self.cursor = ''

    def check_resize_mode(self, x, y):
        width, height = self.Frame1.cget('width'), self.Frame1.cget('height')
        mode = 0
        if x > width-10: mode |= HORIZONTAL    
        if y > height-10: mode |= VERTICAL
        return mode

    def start_resize(self, event):
        self.resize_mode = self.check_resize_mode(event.x, event.y)

    def resize_frame(self, event):
        if self.resize_mode:
            if self.resize_mode & HORIZONTAL:
                self.Frame1.config(width=event.x)
            if self.resize_mode & VERTICAL:
                self.Frame1.config(height=event.y)
        else:
            cursor = 'size' if self.check_resize_mode(event.x, event.y) else ''
            if cursor != self.cursor:
                self.Frame1.config(cursor=cursor)
                self.cursor = cursor

    def stop_resize(self, event):
        self.resize_mode = 0

root = Tk()
root.geometry("800x600+400+50")
App(root)
root.mainloop()

关于python - Tkinter - 使用绑定(bind)动态调整框架大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54767062/

相关文章:

python - Python 中的递归、内存和可变默认参数

python - 如何在 python 中 append 用户输入(整数)和字符串?

python - 读取文本文件的下一行?

python - tkinter:在父级中显示的 Toplevel 中的框架

python - 如何打印 sphinx 项目中定义的所有标签?

python - 如果我必须直接单击横幅并在另一个选项卡上打开它,如何使用 selenium 获取重定向链?

python - 如何使用python将嵌套子节点添加到xml文档中的父节点?

python - 我们如何合并两个数据框而不丢失Python中的任何行

python - 在 Tk 小部件中显示标准输出

Python Tkinter - 在窗口中均匀调整小部件的大小