You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Tkinter尺寸从像素转为毫米?修复TclError报错

Fixing TclError When Trying to Use Millimeters in Tkinter

Got it, let's sort out this issue for you. The error you're seeing (expected integer but got "25m") happens because Tkinter doesn't natively support millimeter units for geometry, font sizes, or widget dimensions. When you append "m" to your values, the underlying Tcl interpreter can't parse them as valid integers (which it expects for these parameters).

The Solution: Convert Millimeters to Pixels

To get consistent physical sizes across different screens, we need to convert millimeters to pixels using the screen's DPI (dots per inch). Here's how to do it properly:

  1. Calculate DPI: Use Tkinter's built-in winfo_fpixels('1i') to get the number of pixels per inch (this works cross-platform).
  2. Conversion Formula: Since 1 inch = 25.4 millimeters, the conversion is:
    pixels = millimeters * DPI / 25.4
    
  3. Apply the Conversion: Use this formula to convert all your millimeter values to integers (since Tkinter expects integer pixel values).

Working Code Example

import tkinter as tk  # Use 'import Tkinter as tk' for Python 2

root = tk.Tk()

# Function to convert millimeters to pixels
def mm_to_px(mm):
    # Get pixels per inch (DPI)
    dpi = root.winfo_fpixels('1i')
    # Convert mm to px and round to integer
    return int(mm * dpi / 25.4)

# Convert window dimensions from mm to px
window_width = mm_to_px(361)
window_height = mm_to_px(203)
root.geometry(f"{window_width}x{window_height}")

# Convert label font size from mm to px
label_font_size = mm_to_px(25)
a = tk.Label(root, text="hello everyone", font=('Helvetica', label_font_size), anchor='center')
# Make label fill the entire window
a.place(x=0, y=0, width=window_width, height=window_height)

# Convert button position and size from mm to px
btn_x = mm_to_px(10)
btn_y = mm_to_px(50)
btn_width = mm_to_px(25)
btn_height = mm_to_px(100)
b1 = tk.Button(root, text="pal entry")
# Use place() to set pixel-based position and size (Button's height/width are character units!)
b1.place(x=btn_x, y=btn_y, width=btn_width, height=btn_height)

root.mainloop()

Key Notes

  • Why winfo_fpixels('1i')? This method safely retrieves the screen's DPI without relying on platform-specific libraries (like win32api for Windows), making your code cross-platform.
  • Button Dimensions: The height and width parameters of Button are measured in character units, not pixels. To set pixel-based sizes, use the width and height arguments in the place() method instead.
  • Consistency: This conversion ensures your UI elements have the same physical size regardless of the screen's resolution or scaling settings.

内容的提问来源于stack exchange,提问作者user9465400

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:04:18