python - 与滚动区域宽度相关的画布项宽度
问题描述
在我的原始代码中,我正在做类似下面的事情,只是有更多的数学运算。
它有效,但我不喜欢在计算矩形的宽度时,我可以看到滚动条(hscrbar)的拇指如何从位置 0 移动到 1 get_width(self):
。因为在我的原始代码中,每次添加内容时我都需要查看它。
目前我还没有解决这个问题的想法,您可能知道解决方案。
import tkinter as tk
root = tk.Tk()
class my_figure(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.root = self.winfo_toplevel()
# DownFrame
self.button = tk.Button(self, text='add', command=self.add)
self.button.grid(column=0, row=0)
self.body = tk.Frame(self, relief='sunken')
self.hscrbar = tk.Scrollbar(self.body, orient=tk.HORIZONTAL)
self.vscrbar = tk.Scrollbar(self.body)
self.Display = tk.Canvas(self.body,
xscrollcommand=self.hscrbar.set,
yscrollcommand=self.vscrbar.set)
self.hscrbar.config(command=self.Display.xview)
self.body.grid(column=0, row=1, sticky='nswe')
self.vscrbar.grid(column=1,sticky='ns')
self.hscrbar.grid(row=1, column=0, sticky='we')
self.Display.grid(column=0, row=0,
sticky='nswe')
self.vscrbar.config(command=self.Display.yview)
self.hscrbar.config(command=self.Display.xview)
self.x = tk.IntVar()
self.y = tk.IntVar()
self.x.set(10)
self.y.set(10)
self.height = 10
def add(self):
self.Display.create_rectangle(self.x.get(),self.y.get(),self.get_width(),self.height)
self.old_x = self.x.get()
self.old_y = self.y.get()
self.x.set(self.old_x+40)
self.y.set(self.old_y+20)
self.Display.config(scrollregion=self.Display.bbox("all"))
def get_width(self):
if self.hscrbar.get()[0] == 0 and self.hscrbar.get()[1] == 1: #if scrollbar shows everything
return self.Display.winfo_width()#return width of the canvas
else:
self.Display.xview_moveto(0) #scrollbar at postition 0
self.root.update_idletasks() #update idletasks to get correct value
value = self.Display.winfo_width()-round(self.Display.winfo_width()*self.hscrbar.get()[1])
width = value+self.Display.winfo_width() #calculate the width
self.Display.xview_moveto(1) #move to position 1 to show my the end of rectangel
return width
figure = my_figure(root)
figure.grid()
root.mainloop()
解决方案
我的猜测是,问题主要是由于get_width
您内部正在移动滚动条,调用update_idletasks
,然后再次移动滚动条。该调用update_idletasks
导致窗口重绘。重绘意味着您会看到滚动条向左移动,然后在函数完成后它会向右移动。
目前还不完全清楚get_width
应该做什么,但我猜你可以删除所有代码并将其替换为self.Display.bbox("all")
,然后从结果中获取 x 坐标来计算绘图的宽度。
推荐阅读
- visual-studio-code - 为什么“clang-format”扩展名不能格式化我的 .sp 文件?
- c# - 通过 Windows 服务调用时,Oracle 查询执行需要时间
- css - 如何使用角度的p-table为第二个表格的一行添加颜色?
- html - Img-fluid 类未在移动设备大小的 Bootstrap 上显示图像
- scala - Xgboost4j - java.lang.NoClassDefFoundError: scala/Product$class 错误
- node.js - 如何在 mongoDb 中加入多个集合
- php - 如何将 Elementor 模板仅分配给存档/类别的第一页
- sapui5 - 有没有办法让 vizType="stacked_combination" 中的列变成 100 个堆叠列?
- c++builder - 在 C++ Builder 中转储当前局部变量(或在其中执行搜索)
- java - 我想创建一个硒脚本来检查所选类型是产品图像还是其他网站是用角度制作的,我可以找到文本