如何调整带图片的customtkinter.CTkLabel组件内文本位置
CustomTkinter CTkLabel 带图片时微调文本位置的解决方案
当使用CustomTkinter的CTkLabel同时设置图片和文本时,默认文本会居中显示,无法通过justify或anchor参数调整位置,导致文本与图片内的元素(如示例中的"Temperature (*F)")位置偏差。
方案1:使用text_offset参数快速微调
CTkLabel内置了text_offset参数,接受(x, y)格式的元组,用于设置文本相对于图片的偏移量,适合小幅度调整:
self.value_box_image = ctk.CTkImage(Image.open("temperature_box.png"), size=(280, 142)) self.temperature_label = ctk.CTkLabel( self.data_frame, text="90", font=ctk.CTkFont(size=60, weight="bold"), corner_radius=50, text_color="black", image=self.value_box_image, text_offset=(0, 15) # 调整x/y数值控制文本偏移,比如向下偏移15像素 ) self.temperature_label.grid(row=1, column=0, pady=(20, 10), sticky="e")
方案2:嵌套组件实现完全自定义定位
如果需要更精准的控制,可以将图片和文本拆分为独立的CTkLabel,放在一个CTkFrame容器中,通过place方法自由定位文本:
self.value_box_image = ctk.CTkImage(Image.open("temperature_box.png"), size=(280, 142)) # 创建容器Frame,保持和原标签一致的圆角 self.temp_container = ctk.CTkFrame(self.data_frame, corner_radius=50) self.temp_container.grid(row=1, column=0, pady=(20, 10), sticky="e") # 放置图片标签,铺满容器 self.image_label = ctk.CTkLabel(self.temp_container, image=self.value_box_image, text="") self.image_label.grid(row=0, column=0, sticky="nsew") self.temp_container.grid_rowconfigure(0, weight=1) self.temp_container.grid_columnconfigure(0, weight=1) # 放置文本标签,用place精准定位 self.temperature_label = ctk.CTkLabel( self.temp_container, text="90", font=ctk.CTkFont(size=60, weight="bold"), text_color="black" ) # relx/rely是相对容器的位置,anchor设置对齐方式 self.temperature_label.place(relx=0.5, rely=0.6, anchor="center")
内容的提问来源于stack exchange,提问作者Sir Absolute 0
相关产品推荐
相关产品推荐

